package cn.hhchat.wp.entity;

import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;

import cn.hhchat.wp.dto.form.CreateGroupForm;
import cn.hhchat.wp.dto.group.SimpleGroup;
import cn.hhchat.wp.repository.JoinRelationRepository;
import cn.hhchat.wp.util.DateUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created this one by HMH on 2017/10/22.
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "group_entity")
public class GroupEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(columnDefinition = "LONGTEXT")
    private String description;

    @CreationTimestamp
    private Date createTime;

    @UpdateTimestamp
    private Date updateTime;

    private Boolean isFinished = false;

    private String postTemplate = "\n" +
            "## {YYYY} 年第 {WW} 周周报\n\n" +
            "### 本周完成\n" +
            "1. 开始写...\n" +
            "\n" +
            "### 下周计划\n" +
            "1. 开始写...\n";

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private UserEntity owner;

    @OneToMany
    @Cascade(CascadeType.SAVE_UPDATE)
    private List<SubscribeRelationEntity> subscribeRelations;

    @OneToMany
    @Cascade(CascadeType.SAVE_UPDATE)
    private List<JoinRelationEntity> joinRelations;

    public GroupEntity(CreateGroupForm form) {
        this.joinRelations = new ArrayList<>();
        this.description = form.getDescription();
        this.name = form.getName();
        this.subscribeRelations = new ArrayList<>();
    }

    @JsonIgnore
    public String getStatus() {
        return this.getIsFinished() ? "终了" : "进行中";
    }

    @JsonIgnore
    public SimpleGroup toSimpleGroup() {
        SimpleGroup simpleGroup = new SimpleGroup();
        simpleGroup.setId(this.id);
        simpleGroup.setName(this.name);
        simpleGroup.setDescription(this.description);
        simpleGroup.setCreateTime(DateUtil.formatDate(this.createTime));
        simpleGroup.setOwner(this.owner.toSimpleUser());
        simpleGroup.setPostTemplate(this.getPostTemplate());
        return simpleGroup;
    }

}
